package org.light.complexverb;

import java.util.ArrayList;
import java.util.List;

import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.DragonHideStatement;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.StatementList;
import org.light.domain.Type;
import org.light.easyui.EasyUIPositions;
import org.light.utils.MybatisSqlReflector;
import org.light.utils.PgsqlReflector;
import org.light.utils.StringUtil;
import org.light.utils.WriteableUtil;

public class Assign extends TwoDomainVerb implements EasyUIPositions {

	@Override
	public Method generateDaoImplMethod() throws Exception {
		Method method = new Method();
		if (StringUtil.isBlank(this.slave.getAlias())){			
			method.setStandardName("Assign"+this.slave.getCapFirstDomainName()+"To"+this.master.getCapFirstDomainName());		
		} else {
			method.setStandardName("Assign"+StringUtil.capFirst(this.slave.getAlias())+"To"+this.master.getCapFirstDomainName());
		}
		method.setNoContainer(false);
		method.addSignature(new Signature(1, "db","*sql.DB"));
		method.addSignature(new Signature(2, "tx","*sql.Tx"));
		method.addSignature(new Signature(3, this.master.getLowerFirstDomainName()+"Id",this.master.getDomainId().getFieldType()));
		method.addSignature(new Signature(4, this.slave.getLowerFirstDomainName()+"Id",this.slave.getDomainId().getFieldType()));
		method.setReturnType(this.slave.getDomainId().getRawType());
		
		List<Writeable> sList = new ArrayList<Writeable>();
		
		if (StringUtil.isBlank(this.getDbType())||this.getDbType().equalsIgnoreCase("MariaDB")||this.getDbType().equalsIgnoreCase("MySQL")) {
			sList.add(new Statement(1000L,1,"sql := \""+ MybatisSqlReflector.generateInsertLinkTwoSql(master,slave)+"\""));
		}else if (this.getDbType().equalsIgnoreCase("PostgreSQL")||this.getDbType().equalsIgnoreCase("pgsql")) {
			sList.add(new Statement(1000L,1,"sql := \""+ PgsqlReflector.generateInsertLinkTwoSql(master,slave)+"\""));
		}	

		sList.add(new Statement(2000L,1,"stmt, err := db.Prepare(sql)"));
		sList.add(new Statement(3000L,1,"if err != nil {"));
		sList.add(new Statement(4000L,2,"panic(err)"));
		sList.add(new Statement(5000L,1,"}"));
		sList.add(new Statement(6000L,1,"result, err := stmt.Exec("+this.master.getLowerFirstDomainName()+"Id, "+this.slave.getLowerFirstDomainName()+"Id)"));
		sList.add(new Statement(7000L,1,"if err != nil {"));
		sList.add(new Statement(8000L,2,"panic(err)"));
		sList.add(new Statement(9000L,1,"}"));
		sList.add(new Statement(10000L,1,"var returnid int64"));
		sList.add(new Statement(11000L,1,"returnid, err = result.LastInsertId()"));
		sList.add(new Statement(12000L,1,"return returnid"));
		method.setMethodStatementList(WriteableUtil.merge(sList));
		return method;
	}
	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		Method method = new Method();
		if (StringUtil.isBlank(this.slave.getAlias())){			
			method.setStandardName("Assign"+this.slave.getCapFirstDomainName()+"To"+this.master.getCapFirstDomainName());		
		} else {
			method.setStandardName("Assign"+StringUtil.capFirst(this.slave.getAlias())+"To"+this.master.getCapFirstDomainName());
		}
		method.setReturnType(new Type("int64"));
		
		method.addSignature(new Signature(1, StringUtil.lowerFirst(this.master.getStandardName())+"Id", this.master.getDomainId().getClassType(),this.master.getPackageToken(),"Param(value=\"" + this.master.getLowerFirstDomainName() + "Id\")"));
		if (StringUtil.isBlank(this.slave.getAlias())){			
			method.addSignature(new Signature(2, StringUtil.lowerFirst(this.slave.getStandardName())+"Id", this.slave.getDomainId().getClassType(),this.slave.getPackageToken(),"Param(value=\"" + this.slave.getLowerFirstDomainName() + "Id\")"));
		}else{
			method.addSignature(new Signature(2, StringUtil.lowerFirst(this.slave.getAlias())+"Id", this.slave.getDomainId().getClassType(),this.slave.getPackageToken(),"Param(value=\"" + StringUtil.lowerFirst(this.slave.getAlias()) + "Id\")"));
		}
		return method;
	}
	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		Method method = new Method();
		method.setStandardName(StringUtil.capFirst(getVerbName()));
		method.setReturnType(new Type("bool"));
		method.setThrowException(true);
		method.addSignature(new Signature(1, StringUtil.lowerFirst(this.master.getStandardName())+"Id", this.master.getDomainId().getClassType()));
		if (StringUtil.isBlank(this.slave.getAlias())){		
			method.addSignature(new Signature(2, StringUtil.lowerFirst(this.slave.getStandardName())+"Ids", new Type("String")));
		}else{
			method.addSignature(new Signature(2, StringUtil.lowerFirst(this.slave.getAlias())+"Ids", new Type("String")));
		}
		return method;
	}
	@Override
	public Method generateServiceImplMethod() throws Exception {
		Method method = new Method();
		method.setStandardName(StringUtil.capFirst(getVerbName()));
		method.setReturnType(new Type("bool"));
		method.addSignature(new Signature(1, StringUtil.lowerFirst(this.master.getStandardName())+"Id", this.master.getDomainId().getClassType()));
		if (StringUtil.isBlank(this.slave.getAlias())){		
			method.addSignature(new Signature(2, StringUtil.lowerFirst(this.slave.getStandardName())+"Ids", new Type("[] "+this.slave.getDomainId().getRawType())));
		}else {		
			method.addSignature(new Signature(2, StringUtil.lowerFirst(this.slave.getAlias())+"Ids", new Type("[] "+this.slave.getDomainId().getRawType())));
		}
		
		Method daoImplMethod = generateDaoImplMethod();
		String slaveIds = StringUtil.lowerFirst(this.slave.getStandardName())+"Ids";
		if (!StringUtil.isBlank(this.slave.getAlias())){
			slaveIds = StringUtil.lowerFirst(this.slave.getAlias())+"Ids";
		}
		List<Writeable> sList = new ArrayList<Writeable>();
		sList.add(new Statement(1000L,1,"db := database.DB"));
		sList.add(new Statement(2000L,1,"tx, err := db.Begin()"));
		sList.add(new Statement(3000L,1,"if err != nil {"));
		sList.add(new Statement(4000L,2,"panic(err)"));
		sList.add(new Statement(5000L,1,"}"));
		sList.add(new Statement(6000L,1,"for _, v := range "+slaveIds+" {"));
		sList.add(new Statement(7000L,2,this.master.getDaoimplSuffix()+"."+daoImplMethod.getStandardName()+"(db, tx, "+this.master.getLowerFirstDomainName()+"Id, v)"));
		sList.add(new Statement(8000L,1,"}"));
		sList.add(new Statement(9000L,0,""));
		sList.add(new Statement(10000L,1,"tx.Commit()"));
		sList.add(new Statement(11000L,1,"return true"));
		method.setMethodStatementList(WriteableUtil.merge(sList));
		return method;
	}
	@Override
	public Method generateControllerMethod() throws Exception {
		Method method = new Method();
		method.setStandardName(StringUtil.capFirst(getVerbName()));
		method.addSignature(new Signature(1,"c","*gin.Context"));
		method.addAdditionalImport("strings");
		
		String slaveIds = StringUtil.lowerFirst(this.slave.getStandardName())+"Ids";
		if (!StringUtil.isBlank(this.slave.getAlias())){
			slaveIds = StringUtil.lowerFirst(this.slave.getAlias())+"Ids";
		}
		List<Writeable> sList = new ArrayList<Writeable>();
		sList.add(new Statement(1000L,1,"idStr := c.PostForm(\""+this.master.getLowerFirstDomainName()+"Id\")"));
		sList.add(new Statement(2000L,1,this.master.getLowerFirstDomainName()+"Id, _ := strconv.ParseInt(idStr, 10, 64)"));
		sList.add(new Statement(3000L,0,""));
		sList.add(new Statement(4000L,1,"idsStr := c.PostForm(\""+slaveIds+"\")"));
		sList.add(new Statement(5000L,1,"idsStrArr := strings.Split(idsStr, \",\")"));
		sList.add(new Statement(6000L,1,"var "+slaveIds+" []int64 = make([]int64, len(idsStrArr))"));
		sList.add(new Statement(7000L,1,"for i, v := range idsStrArr {"));
		sList.add(new Statement(8000L,2,""+slaveIds+"[i], _ = strconv.ParseInt(v, 10, 64)"));
		sList.add(new Statement(9000L,1,"}"));
		sList.add(new Statement(10000L,1,this.master.getServiceimplSuffix()+"."+this.getVerbName()+"("+this.master.getLowerFirstDomainName()+"Id, "+slaveIds+")"));
		sList.add(new Statement(11000L,1,"SendResponse(c, nil, nil, 0, true)"));
		method.setMethodStatementList(WriteableUtil.merge(sList));
		return method;
	}
	public Assign(Domain master,Domain slave){
		super();
		this.master = master;
		this.slave = slave;
		if (StringUtil.isBlank(this.slave.getAlias())){	
			this.setVerbName("Assign"+this.slave.getCapFirstPlural()+"To"+this.master.getCapFirstDomainName());
		}else {
			this.setVerbName("Assign"+StringUtil.capFirst(this.slave.getAliasPlural())+"To"+this.master.getCapFirstDomainName());
		}
		this.setLabel("分配");
		this.dbType = master.getDbType();
	}

	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		return null;
	}

	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		JavascriptMethod method = new JavascriptMethod();
		method.setSerial(200);
		method.setStandardName(StringUtil.lowerFirst(this.getVerbName()));
		
		StatementList sl = new StatementList();
		if (StringUtil.isBlank(this.slave.getAlias())){	
			sl.add(new Statement(1000,1, "var "+this.slave.getLowerFirstDomainName()+"Ids = new Array();"));
			sl.add(new Statement(2000,1, "var rows = $(\"#myAvailable"+this.slave.getCapFirstPlural()+"\").datalist(\"getSelections\");"));
			sl.add(new Statement(3000,1, "if (isBlank(rows)) {"));
			if ("english".equalsIgnoreCase(this.master.getLanguage())) {
				sl.add(new Statement(4000,1, "$.messager.alert(\"Warning\", \"Please select available "+this.slave.getText()+"！\");"));
			}else {
				sl.add(new Statement(4000,1, "$.messager.alert(\"操作提示\", \"请选择可添加"+this.slave.getText()+"！\");"));
			}
			sl.add(new Statement(5000,1, "return;"));
			sl.add(new Statement(6000,1, "}"));
			sl.add(new Statement(7000,1, "for (var i = 0;i<rows.length;i++){"));
			sl.add(new Statement(8000,1, this.slave.getLowerFirstDomainName()+"Ids[i] = rows[i][\""+this.slave.getDomainId().getLowerFirstFieldName()+"\"]; "));
			sl.add(new Statement(9000,1, "}"));
			sl.add(new Statement(10000,1, "var "+this.master.getLowerFirstDomainName()+"Id = $(\"#my"+this.master.getCapFirstDomainName()+"\").datalist(\"getSelected\")."+this.master.getDomainId().getLowerFirstFieldName()+";"));
			sl.add(new Statement(11000,1, "$.ajax({"));
			sl.add(new Statement(12000,1, "type: \"post\","));
			sl.add(new Statement(13000,1, "url: \"../"+this.master.getControllerPackagePrefix()+this.master.getLowerFirstDomainName()+this.master.getControllerNamingSuffix()+"/"+StringUtil.lowerFirst(this.getVerbName())+"\","));
			sl.add(new Statement(14000,1, "data: {"));
			sl.add(new Statement(15000,1, this.slave.getLowerFirstDomainName()+"Ids:"+this.slave.getLowerFirstDomainName()+"Ids.join(\",\"),"));
			sl.add(new Statement(16000,1, this.master.getLowerFirstDomainName()+"Id:"+this.master.getLowerFirstDomainName()+"Id,"));
			sl.add(new Statement(17000,1, "},"));
			sl.add(new Statement(18000,1, "dataType: 'json',"));
			sl.add(new Statement(19000,1, "success: function(data, textStatus) {"));
			sl.add(new Statement(20000,1, "if (data.success) $(\"#my"+this.master.getCapFirstDomainName()+"\").datalist(\"load\");"));
			sl.add(new Statement(21000,1, "},"));
			sl.add(new Statement(22000,1, "complete : function(XMLHttpRequest, textStatus) {"));
			sl.add(new Statement(23000,1, "},"));
			sl.add(new Statement(24000,1, "error : function(XMLHttpRequest,textStatus,errorThrown) {"));
			sl.add(new Statement(25000,1, "alert(\"Error:\"+textStatus);"));
			sl.add(new Statement(26000,1, "alert(errorThrown.toString());"));
			sl.add(new Statement(27000,1, "}"));
			sl.add(new Statement(28000,1, "});"));
		} else {
			sl.add(new Statement(1000,1, "var "+StringUtil.lowerFirst(this.slave.getAlias())+"Ids = new Array();"));
			sl.add(new Statement(2000,1, "var rows = $(\"#myAvailable"+StringUtil.capFirst(this.slave.getAliasPlural())+"\").datalist(\"getSelections\");"));
			sl.add(new Statement(3000,1, "if (isBlank(rows)) {"));
			if ("english".equalsIgnoreCase(this.master.getLanguage())) {
				sl.add(new Statement(4000,1, "$.messager.alert(\"Warning\", \"Please select available "+this.slave.getAliasText()+"！\");"));
			}else {
				sl.add(new Statement(4000,1, "$.messager.alert(\"操作提示\", \"请选择可添加"+this.slave.getAliasText()+"！\");"));
			}
			sl.add(new Statement(5000,1, "return;"));
			sl.add(new Statement(6000,1, "}"));
			sl.add(new Statement(7000,1, "for (var i = 0;i<rows.length;i++){"));
			sl.add(new Statement(8000,1, StringUtil.lowerFirst(this.slave.getAlias())+"Ids[i] = rows[i][\""+this.slave.getDomainId().getLowerFirstFieldName()+"\"]; "));
			sl.add(new Statement(9000,1, "}"));
			sl.add(new Statement(10000,1, "var "+this.master.getLowerFirstDomainName()+"Id = $(\"#my"+this.master.getCapFirstDomainName()+"\").datalist(\"getSelected\")."+this.master.getDomainId().getLowerFirstFieldName()+";"));
			sl.add(new Statement(11000,1, "$.ajax({"));
			sl.add(new Statement(12000,1, "type: \"post\","));
			sl.add(new Statement(13000,1, "url: \"../"+this.master.getControllerPackagePrefix()+this.master.getLowerFirstDomainName()+this.master.getControllerNamingSuffix()+"/"+StringUtil.lowerFirst(this.getVerbName())+"\","));
			sl.add(new Statement(14000,1, "data: {"));
			sl.add(new Statement(15000,1, StringUtil.lowerFirst(this.slave.getAlias())+"Ids:"+StringUtil.lowerFirst(this.slave.getAlias())+"Ids.join(\",\"),"));
			sl.add(new Statement(16000,1, this.master.getLowerFirstDomainName()+"Id:"+this.master.getLowerFirstDomainName()+"Id,"));
			sl.add(new Statement(17000,1, "},"));
			sl.add(new Statement(18000,1, "dataType: 'json',"));
			sl.add(new Statement(19000,1, "success: function(data, textStatus) {"));
			sl.add(new Statement(20000,1, "if (data.success) $(\"#my"+this.master.getCapFirstDomainName()+"\").datalist(\"load\");"));
			sl.add(new Statement(21000,1, "},"));
			sl.add(new Statement(22000,1, "complete : function(XMLHttpRequest, textStatus) {"));
			sl.add(new Statement(23000,1, "},"));
			sl.add(new Statement(24000,1, "error : function(XMLHttpRequest,textStatus,errorThrown) {"));
			sl.add(new Statement(25000,1, "alert(\"Error:\"+textStatus);"));
			sl.add(new Statement(26000,1, "alert(errorThrown.toString());"));
			sl.add(new Statement(27000,1, "}"));
			sl.add(new Statement(28000,1, "});"));			
		}
		
		method.setMethodStatementList(sl);
		return method;	
	}
}
